package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.dto.LoginResultDto;
import com.heima.admin.entity.AdUser;
import com.heima.common.enums.UserStatusEnum;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.common.util.JwtUtils;
import com.heima.model.admin.dtos.AdUserLoginDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2023-05-25
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    private static final Integer EXPIRE_MINUTE = 120;

    @Autowired
    private BCryptPasswordEncoder encoder;

    @Override
    public LoginResultDto login(AdUserLoginDto userLoginDto) {
        //根据用户名查询用户信息
        LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdUser::getName, userLoginDto.getName());
        AdUser adUserDB = this.getOne(queryWrapper);
        if (adUserDB == null) {
            throw new LeadException(AppHttpCodeEnum.AD_USER_NOT_EXIST);
        }
        //密码匹配
        String passwordDB = adUserDB.getPassword();
        String passwordIn = userLoginDto.getPassword();
        boolean matches = encoder.matches(passwordIn, passwordDB);
        if (!matches) {
            throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //判断用户状态
        Integer status = adUserDB.getStatus();
//        if (!Objects.equals(status, 9)) {
        if (UserStatusEnum.isValid(status)) {
            throw new LeadException(AppHttpCodeEnum.USER_STATUS_ERROR);
        }
        //生成user，token返回
        LoginResultDto resultDto = new LoginResultDto();
        resultDto.setUser(BeanHelper.copyProperties(adUserDB, AdUser.class));
        resultDto.setToken(JwtUtils.generateTokenExpireInMinutes(adUserDB.getId(), EXPIRE_MINUTE));
        return resultDto;
    }
}
